<?php

header('Content-Type: text/html; charset=UTF-8');

class monthGismeteoUaHTMLParser
{
    private $text;
    private $data;
    private $actual_date;

    function __construct($text)
    {
        $this->text = $text;
        $this->parse();
    }

    function getData()
    {
        return $this->data;
    }

    function getActualDate()
    {
        return $this->actual_date;
    }

    private function parse()
    {
        $monthNames = array_combine(
            array('Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'),
            range(1, 12)
        );
        $html = preg_split('/Прогноз составлен<br>/us', $this->text, 2);
        $html = $html[1];

        $createDate = preg_split('/<\\/b>/us', $html, 2);
        $this->actual_date = $this->parseData($createDate[0]);

        $html = preg_split('/<hr[^>]*>/us', $html, 3);
        $html = $html[1];
        $rawMonth = preg_split('/monthname>/us', $html);
        array_shift($rawMonth);

        $parts = array();
        foreach ($rawMonth as $part) {
            preg_match('/^([^<]+)<\\/td>/su', $part, $matches);
            $year = date('Y', $this->actual_date);

            $date_prefix = sprintf('%s-%02d-', $year, $monthNames[$matches[1]]);

            foreach ($this->parseMonth($part) as $day => $data) {
                $parts[$date_prefix.sprintf('%02d', $day)] = $data;
            }
        }

        return $this->data = $parts;
    }

    private function parseData($raw)
    {
        $monthNames = array_combine(
            array('января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'авгуса', 'сентября', 'октября', 'ноября', 'декабря'),
            range(1, 12)
        );

        preg_match('/^(\\d+)\\s+(\\S+)\\s+(\\d+)\\s+/su', trim($raw), $matches);
        return strtotime(sprintf('%04d-%02d-%02d 00:00:00', intval($matches[3]), intval($monthNames[$matches[2]]), intval($matches[1])));
    }

    private function parseMonth($raw)
    {
        $daysNum = array();
        $days = array();
        preg_match_all('/class=day>([^<]+)/su', $raw, $matches, PREG_SET_ORDER);
        foreach ($matches as $k => $v) {
            $days[$k] = array();
            $daysNum[intval($v[1])] = intval($v[1]);
        }
        preg_match_all('/<img\\b[^>]*\\bsrc\\s*=\\s*(\\S+)/su', $raw, $matches, PREG_SET_ORDER);
        foreach ($matches as $k => $v) {
            $days[$k]['image'] = $v[1];
        }
        preg_match_all('/<img\\b[^>]*\\balt\\s*=\\s*\'([^\']+)\'/su', $raw, $matches, PREG_SET_ORDER);
        foreach ($matches as $k => $v) {
            $days[$k]['alt'] = $v[1];
        }
        preg_match_all('/class=temper>([^<]+)/su', $raw, $matches, PREG_SET_ORDER);
        foreach ($days as $k => $null) {
            $i++;
            $day   = array_map('intval', array_map('trim', explode('..', $matches[$i*2-2][1])));
            $night = array_map('intval', array_map('trim', explode('..', $matches[$i*2-1][1])));
            $days[$k]['tDayMin']   = min($day);
            $days[$k]['tDayMax']   = max($day);
            $days[$k]['tNightMin'] = min($night);
            $days[$k]['tNightMax'] = max($night);
        }
        return array_combine($daysNum, $days);
    }
}

function getPogoda($city)
{
    $date = date('Y-m-d');
    $fname = dirname(__FILE__).DIRECTORY_SEPARATOR.'pogoda'.DIRECTORY_SEPARATOR.$city.'.'.$date.'.html';
    if (! file_exists($fname)) {
        $html = file_get_contents('http://month.gismeteo.ua/forecast.php?town='.$city);
        $html = iconv('cp1251', 'UTF-8', $html);
        $h = fopen($fname, 'w');
        fwrite($h, $html);
        fclose($h);
    }

    return file_get_contents($fname);
}

function getData($city)
{
    $date = date('Y-m-d');
    $fname = dirname(__FILE__).DIRECTORY_SEPARATOR.'pogoda'.DIRECTORY_SEPARATOR.$city.'.'.$date.'.txt';
    if (! file_exists($fname)) {
        $parser = new monthGismeteoUaHTMLParser(getPogoda($city));

        $t = $parser->getData();
        $temperatures = array();
        ksort($t);

        $h = fopen($fname, 'w');
        fwrite($h, var_export($t, 1));
        fclose($h);
    }

    eval('$data = '.file_get_contents($fname).';');

    return $data;
}
$CityID = array(
    'Судак' => 33976,
    'Киев' => 33345,
);
$t = getData($CityID['Киев']);

/**
 * d_1_2.gif Ясно
 * d_1_4.gif Без осадков
 * d_3_5.gif Возможен дождь
 * d_9_5.gif Возможен снег
 */

foreach ($t as $date => $data) {
    $date = strtotime($date);
    $temperatures[] = array(
        'y' => intval(date('Y', $date)),
        'm' => intval(date('m', $date)),
        'd' => intval(date('d', $date)),
        'dmin' => $data['tDayMin'],
        'dmax' => $data['tDayMax'],
        'nmin' => $data['tNightMin'],
        'nmax' => $data['tNightMax'],
    );
}

?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Галерея</title>
    <script src="http://code.jquery.com/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="gui.js" type="text/javascript"></script>
<style>
    html, body, div, span, applet, object, iframe,
    h1, h2, h3, h4, h5, h6, p, blockquote, pre,
    a, abbr, acronym, address, big, cite, code,
    del, dfn, em, font, img, ins, kbd, q, s, samp,
    small, strike, strong, sub, sup, tt, var,
    dl, dt, dd, ol, ul, li,
    fieldset, form, label, legend,
    table, caption, tbody, tfoot, thead, tr, th, td {
    	margin: 0;
    	padding: 0;
    	border: 0;
    	outline: 0;
    	font-weight: inherit;
    	font-style: inherit;
    	font-size: 100%;
    	font-family: inherit;
    	vertical-align: baseline;
    }
    /* remember to define focus styles! */
    :focus {
    	outline: 0;
    }
    body {
    	line-height: 1;
    	color: black;
    	background: white;
    }
    ol, ul {
    	list-style: none;
    }
    /* tables still need 'cellspacing="0"' in the markup */
    table {
    	border-collapse: separate;
    	border-spacing: 0;
    }
    caption, th, td {
    	text-align: left;
    	font-weight: normal;
    }
    blockquote:before, blockquote:after,
    q:before, q:after {
    	content: "";
    }
    blockquote, q {
    	quotes: "" "";
    }


    /*====================================================*/

.sys_empty4ie {
    display: none;
    padding: 0px;
    margin: 0px;
    border-width: 0px;
}
* html .sys_empty4ie {
    zoom: 1;
    padding: 0px;
    margin: 0px;
    border-width: 0px;
}



    /*====================================================*/
    /*====================================================*/

    .polosa {
        /*width: 40em;*/
    }
    .block {
        width: 100%;
    }


    /*====================================================*/

    body {
        background-color: #DCB474;
    }
    .polosa {
        background-color: #FFFFFF;
    }
    h1 {
        font-size: 1.73em;
    }
    h2 {
        font-size: 1.44em;
    }
    h3 {
        font-size: 1.2em;
        text-transform: uppercase;
        letter-spacing: 0.15em;
        Line-height: 1.44;
    }
    h4 {
        font-size: 1em;
    }
    h5 {
        font-size: 1em;
    }
    h6 {
        font-size: 1em;
    }
    h1, h2, h3, h4, h5, h6 {
        margin-left: -0.1em;
        margin-top: 0.5em;
        margin-bottom: 0.25em;
    }
    small {
        font-size: 67%
    }
    .ar {
        text-align: right;
    }
    .num1 {
        width: 2em;
        padding-right: 0.7em;
    }
    .pageNum {
        width: 3em;
        padding-right: 0.2em;
        font-size: 120%;
    }
    .pageCount {
        width: 1em;
    }


    .polosa {
        overflow-x: hidden;
        width: 100%;
        position: relative;
    }

    body {
        font-family:Arial,sans-serif;
        line-height:1.4;
    }
    .slides-bar {
        height: 700px;
        position: relative;
    }
    imd.slide {
        height: 600px;
    }



.t-overlay {
    width: 2000px;
    height: 700px;
    left: 0px;
    top: 0px;
    position: absolute;
}
* html .t-overlay {
    background-color: #C7DEF3;
    filter: alpha(opacity=0);
}
*+html .t-overlay {
    background-color: #C7DEF3;
    filter: alpha(opacity=0);
}

</style>

<!--==============================================================================-->
<!--==============================================================================-->


    <script type='text/javascript' src='http://www.google.com/jsapi'></script>
    <script type='text/javascript'>
      google.load('visualization', '1', {'packages':['annotatedtimeline']});
      google.setOnLoadCallback(drawChart);

      var temperatures = <?php
        echo json_encode($temperatures);
      ?>

      function drawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('date', 'Date');

        data.addColumn('number', 'DayMax');
            data.addColumn('string', 'titleDayMax');
            data.addColumn('string', 'textDayMax');

        data.addColumn('number', 'DayMin');
            data.addColumn('string', 'titleDayMin');
            data.addColumn('string', 'textDayMin');

        data.addColumn('number', 'NightMax');
            data.addColumn('string', 'titleNightMax');
            data.addColumn('string', 'textNightMax');

        data.addColumn('number', 'NightMin');
            data.addColumn('string', 'titleNightMin');
            data.addColumn('string', 'textNightMin');

        var rows = [];
        for (i in temperatures) {
           var t = temperatures[i];
            rows[rows.length] =
                [
                    new Date(t['y'], t['m']-1,t['d']),
                    t['dmax'], undefined, undefined,
                    t['dmin'], undefined, undefined,
                    t['nmax'], undefined, undefined,
                    t['nmin'], undefined, undefined
                ];

        }
        data.addRows(rows);

        var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('chart_div'));
        chart.draw(data, {displayAnnotations: true});
      }
    </script>
<!--==============================================================================-->
<!--==============================================================================-->


</head>
<body>
<!--==============================================================================-->
<!--==============================================================================-->



    <!--// Note how you must specify the size of the container element explicitly!-->
    <div id='chart_div' style='width: 1000px; height: 480px;'></div>


<!--==============================================================================-->
<!--==============================================================================-->

</body></html><?php

?>